﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TrangTrai.Data.BO;
using TrangTrai.Data.DAO;
using System.Collections.Specialized;
using System.Data;
namespace Trangtrai.tochuc
{
    public partial class GroupManage : System.Web.UI.Page
    {
        
        GroupManagementDAO dao = new GroupManagementDAO();
        static Dictionary<int, UserInfo> dic = new Dictionary<int, UserInfo>(); // luu danh sach nhan vien da chon cho mot group
        static Dictionary<string, GroupInfo> dicGroups = new Dictionary<string, GroupInfo>(); // luu danh sach nhan vien da chon cho mot group
        static int flagEdit = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            //currentUserList = dgvSelectedUsers.DataSource==null? currentUserList:((UserInfo[])dgvSelectedUsers.DataSource).ToList();
              
            loadData();
              
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            List<object> list = ASPxGridView2.GetSelectedFieldValues(new string[] { "userId","roleName","fullName"});
            foreach(object obj in list){
                object[] temp = (object[])obj;
                UserInfo userInfo = new UserInfo();
                userInfo.userId = (Int32)temp[0];
                userInfo.roleName = (string)temp[1];
                userInfo.fullName = (string)temp[2];
                if(!dic.ContainsKey(userInfo.userId)){
                    dic.Add(userInfo.userId, userInfo);
                }
                
            }
            // binding data to selected user
            dgvSelectedUsers.DataSource = dic.Values;
            dgvSelectedUsers.DataBind();

        }
        // save group info inton db
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var resultcode= validate();
            switch (resultcode){
                case 0:
                    processSave();
                    break;
                default:
                    display(resultcode);
                    break;

                      
            }
            
         }

        private void display(int resultCode)
        {
            if (resultCode == 2)
            {
                lblMess.Text = "Mã đội đã tồn tại";
                lblMess.Visible = true;
                lblMess.ForeColor = System.Drawing.Color.Red;

            }
            else {
                lblMess.Text = "Mã đội hay tên đội là trống";
                lblMess.Visible = true;
                lblMess.ForeColor = System.Drawing.Color.Red;
            }
        }

        protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            //ASPxGridView1.

            
        }

        protected void ASPxGridView1_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            //delete group
                        
            // delete all user in group
             OrderedDictionary dic1 = e.Keys;
             int groupId= (int)dic1[0];
             dao.deleteGroup(groupId);
            // reload group list
             ASPxGridView1.DataSource = dao.getAllGroupListByLinq();
             ASPxGridView1.DataBind();

        }
        private GroupInfo getGroupInfo() {
            GroupInfo groupInfo = new GroupInfo();
            groupInfo.groupName = tbxGroupNewName.Text.Trim();
            groupInfo.groupCode = tbxGroupCode.Text.Trim();
            groupInfo.address = tbxAddress.Text.Trim();
            groupInfo.note = tbxGroupNote.Text.Trim();
            return groupInfo;
        }
        private int validate() {
            // validate existing groupcode
            // validate blank
            GroupInfo groupInfo= getGroupInfo();
            if (String.IsNullOrEmpty(groupInfo.groupCode) || String.IsNullOrEmpty(groupInfo.groupName) )
            {
                return 1;// empty require field.
            }
            else
            {
                // return 0 if ok, 1 for existing group code.
                return dicGroups.ContainsKey(groupInfo.groupCode) && flagEdit==0 ? 2 : 0;
            }
            
        }
        class ErrorCode{
            int codetype { get; set; }
            public ErrorCode(int errorcode) {
                this.codetype = errorcode;
            }
        }
        private void processSave(){
            switch(flagEdit){
                case 1:
                    update();
                    break;
                case 0:
                    addGroup();
                    break;

            }

        }

        private void addGroup()
        {
            // insert group info into group table
            GroupInfo groupInfo = this.getGroupInfo();
            dao.createGroup(getGroupInfo());
            // add user into group.
            GroupInfo temp = dao.GetGroupByCode(groupInfo.groupCode).First();
            dao.addUsersIntoGroup(temp.groupId, dic.Values.ToList());
            dic.Clear();
            // reload group list.

            // display info message
            lblMess.Text = "Lưu thành công.";
            lblMess.Visible = true;
            lblMess.ForeColor = System.Drawing.Color.Blue;
            // reload data
            loadData();
            resetForm();
            ASPxGridView2.Visible = false;
            bntAddNew.Visible = true;
            btnSelect.Visible = false;
        }
        
        private void update(){
            // insert group info into group table
            GroupInfo groupInfo = this.getGroupInfo();
            
            List<object> groupIds = ASPxGridView1.GetSelectedFieldValues(new string[] { "groupId" });
            if (groupIds.Count == 0) return;
            int groupId = Int32.Parse(groupIds[groupIds.Count - 1].ToString());
            groupInfo.groupId = groupId;
            dao.deleteUsersFromGroup(groupInfo.groupId);
            dao.updateGroup(groupInfo);
            dao.addUsersIntoGroup(groupInfo.groupId, dic.Values.ToList());
            
            // display info message
            lblMess.Text = "Lưu thành công.";
            lblMess.Visible = true;
            lblMess.ForeColor = System.Drawing.Color.Blue;
            // reload data
            ASPxGridView2.Visible = false;
            bntAddNew.Visible = true;
            btnSelect.Visible = false;
            dic.Clear();
            loadData();
            resetForm();
           
        }
        private void resetForm() {
            tbxGroupCode.Text = "";
            tbxGroupNewName.Text = "";
            tbxGroupNote.Text = "";
            tbxAddress.Text = "";
        }

         protected void loadDataIntoControls(GroupInfo groupInfo) {
            tbxGroupCode.Text = groupInfo.groupCode;
            tbxGroupNewName.Text = groupInfo.groupName;
            tbxGroupNote.Text = groupInfo.note;
            tbxAddress.Text = groupInfo.address;

        }
        protected void loadData() {
            GroupInfo[] groupInfos = dao.getAllGroupListByLinq();
            ASPxGridView1.DataSource = groupInfos;
            ASPxGridView1.DataBind();
            if (IsPostBack)
            {
                dgvSelectedUsers.DataSource = dic.Values;
                dgvSelectedUsers.DataBind();
            }

            try
            {
                dicGroups = groupInfos.ToDictionary(key => key.groupCode, value => value);
            }
            catch (Exception)
            {

                // throw;
            }
        }

        protected void dgvSelectedUsers_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
           if(e.ButtonID=="txtRemove"){
               UserInfo userInfo= (UserInfo)dgvSelectedUsers.GetRow(e.VisibleIndex);
               if(dic.ContainsKey(userInfo.userId)){
                   dic.Remove(userInfo.userId);
                   dgvSelectedUsers.DataSource = dic.Values;
                   dgvSelectedUsers.DataBind();
               }
           }
        }

        protected void bntDetails_Click(object sender, EventArgs e)
        {
            bntAddNew.Visible = false;
            tbAddDetails.Visible = true;
            enable(false);
            disableDetails(true);
            List<object> groupIds= ASPxGridView1.GetSelectedFieldValues(new string[] { "groupId" });
            if (groupIds.Count == 0) return;
            int groupId = Int32.Parse(groupIds[groupIds.Count-1].ToString());
            GroupInfo groupInfo = dao.getGroupById(groupId);
            loadDataIntoControls(groupInfo);
            dgvSelectedUsers.DataSource = dao.getUsersInGroup(groupId);
            dgvSelectedUsers.DataBind();
            dgvSelectedUsers.Columns[2].Visible = false;
            lblCaption.Text = "Thông tin chi tiết đội";
            dic.Clear();

        }


        protected void bntEdit_Click(object sender, EventArgs e)
        {
            bntAddNew.Visible = true;
            tbAddDetails.Visible = true;
            enable(false);
            disableDetails(false);
            List<object> groupIds = ASPxGridView1.GetSelectedFieldValues(new string[] { "groupId" });
            if (groupIds.Count == 0) return;
            int groupId = Int32.Parse(groupIds[groupIds.Count - 1].ToString());
            GroupInfo groupInfo = dao.getGroupById(groupId);
            loadDataIntoControls(groupInfo);
            UserInfo [] userInfos= dao.getUsersInGroup(groupId);
            dgvSelectedUsers.DataSource = userInfos;
            dgvSelectedUsers.DataBind();
            dic = userInfos.ToDictionary(x => x.userId, x => x);
            dgvSelectedUsers.Columns[2].Visible = true;
            lblCaption.Text = "Sửa thông tin đội";
            flagEdit = 1;

        }

        protected void bntDelete_Click(object sender, EventArgs e)
        {
            // delete user from group
            // get groupid
            List<object> groupIds = ASPxGridView1.GetSelectedFieldValues(new string[] { "groupId" });
            if (groupIds.Count == 0) return;
            int groupId = Int32.Parse(groupIds[groupIds.Count-1].ToString());
            dao.deleteGroup(groupId);
            dao.deleteUsersFromGroup(groupId);
            ASPxGridView1.DataSource= dao.getAllGroupListByLinq();
            ASPxGridView1.DataBind();
            enable(false);
            resetForm();
            
        }

        protected void bntAddNew_Click(object sender, EventArgs e)
        {
            bntAddNew.Visible = false;
            enable(true);
            disableDetails(false);
            ASPxGridView2.DataSource = dao.getAllUsers();
            ASPxGridView2.DataBind();
            btnSelect.Visible = true;

           

        }
        private void enable(bool isDisable) {
            ASPxGridView2.Visible = isDisable;
            btnSelect.Visible = isDisable;
        }
        private void disableDetails(bool isReadonly) {
            tbxGroupCode.ReadOnly = isReadonly;
            tbxGroupNewName.ReadOnly = isReadonly;
            tbxAddress.ReadOnly = isReadonly;
            tbxGroupNote.ReadOnly = isReadonly;
        }

        protected void btnAddGroup_Click(object sender, EventArgs e)
        {
            tbAddDetails.Visible = true;
            bntAddNew.Visible = true;
            disableDetails(false);
            lblCaption.Text = "Thêm mới đội";
            resetForm();
            flagEdit = 0;
        }

       
    }
}
